package com.xb.system.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

/**
 * 微信支付工具类
 */
@Slf4j
public class WechatPayUtil {

    private static final String UNIFIED_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";

    /**
     * 生成随机字符串
     * @return 随机字符串
     */
    public static String generateNonceStr() {
        Random random = new Random();
        return DigestUtils.md5Hex(String.valueOf(random.nextInt(10000)));
    }

    /**
     * 生成签名
     * @param params 参数
     * @param key 密钥
     * @return 签名
     */
    public static String generateSign(Map<String, String> params, String key) {
        TreeMap<String, String> sortedParams = new TreeMap<>(params);
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : sortedParams.entrySet()) {
            String k = entry.getKey();
            String v = entry.getValue();
            if (!"sign".equals(k) && v != null && !"".equals(v)) {
                sb.append(k).append("=").append(v).append("&");
            }
        }
        sb.append("key=").append(key);
        return DigestUtils.md5Hex(sb.toString()).toUpperCase();
    }

    /**
     * 调用统一下单接口，获取支付二维码链接
     * @param params 参数
     * @return 支付二维码链接
     */
    public static String createUnifiedOrder(Map<String, String> params) {
        try {
            String xml = XMLUtil.mapToXml(params);
            log.info("统一下单接口请求参数：{}", xml);
            
            String responseXml = httpPost(UNIFIED_ORDER_URL, xml);
            log.info("统一下单接口响应：{}", responseXml);
            
            Map<String, String> responseMap = XMLUtil.xmlToMap(responseXml);
            
            if ("SUCCESS".equals(responseMap.get("return_code")) && "SUCCESS".equals(responseMap.get("result_code"))) {
                return responseMap.get("code_url");
            } else {
                log.error("统一下单失败：{}", responseMap.get("return_msg"));
                return null;
            }
        } catch (Exception e) {
            log.error("调用统一下单接口异常", e);
            return null;
        }
    }

    /**
     * 验证签名
     * @param params 参数
     * @param key 密钥
     * @return 是否验证通过
     */
    public static boolean verifySign(Map<String, String> params, String key) {
        String sign = params.get("sign");
        if (sign == null) {
            return false;
        }
        String calculatedSign = generateSign(params, key);
        return sign.equals(calculatedSign);
    }

    /**
     * 发送HTTP POST请求
     * @param url 请求URL
     * @param data 请求数据
     * @return 响应数据
     */
    private static String httpPost(String url, String data) throws Exception {
        URL urlObj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
        
        try (OutputStream os = conn.getOutputStream()) {
            os.write(data.getBytes("UTF-8"));
            os.flush();
        }
        
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        }
        
        return sb.toString();
    }
} 